<template>
  <el-select style="width: 100%" v-bind="$attrs" ref="select" v-model="deptName">
    <el-option
        value=""
        style="width: 100%;height:200px;overflow: auto;background-color:#fff"
        v-loading="loading">
      <el-tree :data="deptTree" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
    </el-option>
  </el-select>
</template>

<script>
import VueUtil from "@/util/VueUtil";
import {NuoDeptController} from "@/actions/controller";

export default {
  name: "select-company",
  props:{
     value: String,
     name: String,
     isCompany: {
       type: Boolean,
       default: false
     },
    destroy:{
       type : Boolean,
        default: false
    }
  },
  emits: ["update:value","update:name"],
  data(){
    return{
      deptTree: [
        {
          name: '根节点',
          id: '0',
          children:[]
        }
      ],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      deptName: '',
      loading: false
    }
  },
  watch:{
    name:{
      handler(newName){
        if(newName){
          this.deptName = newName
        }
      },
      immediate: true
    },
    destroy:{
      handler(newName) {
        if(!newName){
         this.close()
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.init()
  },
  methods: {
     init(){
      this.loading = true
       let dataForm = {}
       if(this.isCompany){
         dataForm.isCompany = 1
       }
      VueUtil(this).ajax(NuoDeptController.queryAllDept,dataForm).then(res =>{
        this.deptTree[0].children = res.data
        this.loading = false
      }).catch(()=>{
        this.loading = false
      })
    },
    handleNodeClick(data){
       this.deptName = data.name
       this.$emit("update:value",data.id)
      this.$emit("update:name",this.deptName)
      this.$refs.select.blur()
    },
    close(){
      this.deptName = ''
    }
  }
}
</script>

<style scoped>

</style>